package collect;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import bean.NodeBean;
import bean.NodeTypeBean;

public class WorkThread extends Thread{
	
	NodeTypeBean nodeType;
	NodeBean node;
	String outputPath;
	Vector<String> midData;
	
	public WorkThread(NodeBean node,NodeTypeBean nodeType,String outputPath) {
		this.nodeType = nodeType;
		this.node = node;
		this.outputPath = outputPath;
	}
	
	public void run() {
		if (exeTelnet()) {
			parseFile();
		}	
	}
	
	private boolean exeTelnet() {
		System.out.println(new Date() + ":begin telnet task for node:"+node.ipaddress);
		
		TelnetUtil telnet = new TelnetUtil(nodeType.termtype,
				nodeType.commandPrompt); // Windows,用VT220,否则会乱码
		telnet.loginPrompt = nodeType.loginPrompt;
		telnet.passwordPrompt = nodeType.passwordPrompt;
		if (!telnet.login(node.ipaddress, node.port, node.user, node.password)) return false;

		List<String> commands = (ArrayList) nodeType.commands;
		StringBuffer sb = new StringBuffer();
		for (String command : commands) {
			System.out.println("command is:"+command);
			if (command.startsWith("$sleep")) {// 休眠
				try {
					Thread.sleep(Integer.valueOf(command.split(":")[1])
							.intValue() * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				continue;
			}
			
			boolean promptFlag = command.indexOf("|") > 0;  //更改提示符
			boolean outFlag = command.indexOf("[midData]") > 0; //输出有变量
			boolean inFlag = command.indexOf("{midData}") > 0; //输入有变量
			boolean paramFlag = command.indexOf("midData") > 0; //命令有变量
			boolean complexFlag = command.indexOf("^^") > 0; //复合命令
			boolean twoPromptFlag = promptFlag && command.indexOf(",") > 0; //需中间干预的命令
			
			if (!promptFlag && !paramFlag && !complexFlag) { //普通命令
				sb.append(telnet.sendCommand(command));
				continue;
			}
			
			if (promptFlag && !complexFlag && !paramFlag) { // 有提示符的单条无变量命令
				String[] ss = command.split("\\|");
//				if (twoPromptFlag) { //需中间干预的命令
//					String[] pps = ss[1].split(",");
//					telnet.setPrompt(pps[1]);
//					System.out.println("Workthread send command2:"+ss[0]+","+pps[0]);
//					sb.append(telnet.sendCommand2(ss[0],pps[0]));
//					continue;
//				}
				if (twoPromptFlag) {
					sb.append(dealTwoPromptCommand(ss,telnet));
					continue;
				}
				
				telnet.setPrompt(ss[1]);
				if (ss[0].equals("$password")) { //需输入密码
					command = node.password;
				} else {
					command = ss[0];
				}
				sb.append(telnet.sendCommand(command));
				continue;
			}
			
			String commandOut;
			if (outFlag ) {	
				command = command.substring(0,command.indexOf("[midData]"));
				if (twoPromptFlag) { //有提示符的变量
					String[] ss = command.split("\\|");
					commandOut = dealTwoPromptCommand(ss,telnet);
				} else { //无提示符的变量命令
					commandOut = telnet.sendCommand(command);
				}
				preParse(commandOut);
				sb.append(commandOut);
				continue;
			}
			
			if (inFlag) {
				StringBuffer midSb = new StringBuffer();
				String tempCommand = command;
				
				for (int k=0;k<midData.size();k++) {	
		    		command = tempCommand.replace("{midData}",midData.get(k));
		    		if ( complexFlag ) { //复合命令
		    			String[] incommands = command.split("\\^\\^");
		    			midSb.append(telnet.sendCommand(incommands[0]));//先执行第一条
		    			if (twoPromptFlag) { //执行第二条(需干预)
		    				String[] ss = incommands[1].split("\\|");
		    				midSb.append(dealTwoPromptCommand(ss,telnet));
		    			} else { //无需干预(暂无此情况)
		    				midSb.append(telnet.sendCommand(incommands[1]));
		    			}
		    		} else {//无需干预的单命令(暂没有需干预的单命令情况)
		    			midSb.append(telnet.sendCommand(command));
		    		}		    		
		    	}
		    	sb.append(midSb.toString());
		    } 
			//sb.append(new String(telnet.sendCommand(command).getBytes("ISO-8859-1"),"GBK"));
			
		}
		telnet.disconnect();
		//生成文件
//		System.out.println(sb.toString());		
//		java.text.DateFormat format2 = new java.text.SimpleDateFormat("yyyyMMddHHmm");
//        String now = format2.format(new Date());
//		File file=new File("F:/tims/"+node.ipaddress+"-"+now+".log");
		String outfileName = outputPath + node.ipaddress + ".log";
		File file=new File(outfileName);
        try {
			if(!file.exists()) {
			    file.createNewFile();
			}    
			FileOutputStream out=new FileOutputStream(file,false);        
			out.write(sb.toString().getBytes());                
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println(new Date() + ":1exeTelnet ok for node:" + node.ipaddress);
        return true;
        
	}
	
	private void parseFile() {
		String parser = nodeType.parser;
		String file = outputPath + node.ipaddress + ".log";
		try {
			//Class对象描述了某个特定的类对象  
			Class<?> classType = Class.forName(parser);  
			//通过反射生成一个IParser类型的对象  
			Object o = classType.newInstance();    
			//通过反射获取到parse方法  
			Method parseMethod = classType.getMethod("parse", new Class[]{String.class});  
			  
			//调用对象的parse方法并把参数传进去  
			parseMethod.invoke(o,new Object[]{file});
			
			System.out.println(new Date() + ":2parseFile ok for node:" + node.ipaddress);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	private void preParse(String midString) {
		String parser = nodeType.parser;		
		try {
			//Class对象描述了某个特定的类对象  
			Class<?> classType = Class.forName(parser);  
			//通过反射生成一个IParser类型的对象  
			Object o = classType.newInstance();    
			//通过反射获取到parse方法  
			Method parseMethod = classType.getMethod("preParse", new Class[]{String.class});  
			  
			//调用对象的parse方法并把参数传进去  
			midData = (Vector<String>)parseMethod.invoke(o,new Object[]{midString});
			
			System.out.println(new Date() + ":0preParse ok for node:" + node.ipaddress);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	private String dealTwoPromptCommand(String[] ss,TelnetUtil telnet) {		
		String[] pps = ss[1].split(",");
		telnet.setPrompt(pps[1]);
		//System.out.println("Workthread send command2:"+ss[0]+","+pps[0]);
		return telnet.sendCommand2(ss[0],pps[0]);
	}
	
	public static void main(String[] args) {
//		String command = "interface pon {midData}^^show mac-addr table|More--,#";
//		boolean complexFlag = command.indexOf("^^") > 0;
//		System.out.println(complexFlag);
//		command = command.replace("{midData}", "5/2");
//		if (command.indexOf("^^") > 0 ) { //复合命令
//			System.out.println(command);
//			String[] incommands = command.split("\\^\\^");
//			System.out.println((incommands[0]));//先执行第一条
//			String[] ss = incommands[1].split("\\|");
//			System.out.println(ss[0]);
//			System.out.println(ss[1]);
//		}	
		String command = "show fdbentry mac {midData}";
		Vector<String> midData = new Vector();
		midData.add("1");
		midData.add("2");
		midData.add("3");
		for (int k=0;k<midData.size();k++) {
			System.out.println(midData.get(k));
			System.out.println(command.replace("{midData}",midData.get(k)));
		}
	}
}
